import { Vec3 } from '@/core/types';
import { Entity } from '@/entities/Entity';
import {
    ChatMessage,
    ConversationContext,
    ChatState,
    ChatEvent,
    ChatEventType,
    GameContext
} from './types';
import { getEntityPersona, getRandomGreeting } from './EntityPersonas';
import { aiService, fallbackService } from './AIService';
import { configUI } from './ConfigUI';
import { chatStorage, StoredChatMessage } from './ChatStorage';
import { TargetSelector } from './TargetSelector';

export class ChatManager {
    private state: ChatState;
    private conversations: Map<string, ConversationContext>;
    private eventListeners: Map<ChatEventType, Function[]>;
    private maxDetectionRange = 5; // 检测范围
    private maxChatRange = 10; // 对话范围
    private gameContextProvider?: (entity: Entity) => GameContext;
    private targetSelector: TargetSelector;

    constructor() {
        this.state = {
            isActive: false,
            currentTarget: null,
            currentConversation: null,
            isWaitingForResponse: false,
            lastError: null
        };
        this.conversations = new Map();
        this.eventListeners = new Map();
        
        // 初始化目标选择器
        this.targetSelector = new TargetSelector(this.maxDetectionRange);
        
        // 初始化聊天存储
        this.initializeChatStorage();
    }

    // 初始化聊天存储
    private async initializeChatStorage(): Promise<void> {
        try {
            await chatStorage.initialize();
            console.log('ChatStorage initialized in ChatManager');
        } catch (error) {
            console.error('Failed to initialize ChatStorage:', error);
        }
    }

    // 开始对话
    async startConversation(entity: Entity): Promise<void> {
        if (!entity || !this.canChatWithEntity(entity)) {
            return;
        }

        const entityId = entity.getId();
        const entityType = entity.getType();

        // 设置当前目标
        this.state.currentTarget = entity;
        this.state.isActive = true;
        
        // 通知目标选择器对话已开始
        this.targetSelector.setConversationInProgress(true);

        // 获取或创建对话上下文
        let conversation = this.conversations.get(entityId);
        if (!conversation) {
            // 从存储中加载历史记录
            const history = await this.loadConversationHistory(entityId, entityType);
            
            conversation = {
                entityId,
                entityType,
                history,
                gameContext: this.getGameContext(entity)
            };
            this.conversations.set(entityId, conversation);

            // 如果没有历史记录，添加问候消息
            if (history.length === 0) {
                const greeting = getRandomGreeting(entityType);
                await this.addMessage(entityId, 'entity', greeting, {
                    messageType: 'conversation',
                    trigger: 'player_approach',
                    importance: 'medium'
                });
            }
        }

        this.state.currentConversation = conversation;
        this.emitEvent('conversation_started', { entity, conversation });
    }

    // 结束对话
    endConversation(): void {
        if (this.state.currentTarget) {
            this.emitEvent('conversation_ended', {
                entity: this.state.currentTarget,
                conversation: this.state.currentConversation
            });
        }

        this.state.isActive = false;
        this.state.currentTarget = null;
        this.state.currentConversation = null;
        this.state.isWaitingForResponse = false;
        
        // 通知目标选择器对话已结束
        this.targetSelector.setConversationInProgress(false);
    }

    // 发送消息
    async sendMessage(message: string): Promise<void> {
        if (!this.state.currentConversation || !this.state.currentTarget) {
            throw new Error('没有选择对话目标');
        }

        const entityId = this.state.currentTarget.getId();
        const entityType = this.state.currentTarget.getType();

        // 添加玩家消息
        await this.addMessage(entityId, 'player', message, {
            messageType: 'conversation',
            trigger: 'player_message',
            importance: 'medium'
        });
        this.emitEvent('message_sent', { message, entityId });

        // 设置等待状态
        this.state.isWaitingForResponse = true;
        this.emitEvent('ai_thinking_start', { entityId });

        try {
            // 生成AI回复
            const response = await this.generateAIResponse(message, this.state.currentConversation);
            
            // 添加AI回复
            await this.addMessage(entityId, 'entity', response, {
                messageType: 'conversation',
                trigger: 'player_message',
                importance: 'medium'
            });
            this.state.lastError = null;
        } catch (error) {
            console.error('AI回复生成失败:', error);
            
            // 使用备用回复
            const fallbackResponse = fallbackService.getFallbackResponse(entityType);
            await this.addMessage(entityId, 'entity', fallbackResponse, {
                messageType: 'system',
                trigger: 'player_message',
                importance: 'low'
            });
            
            this.state.lastError = (error as Error).message;
            this.emitEvent('error_occurred', { error: (error as Error).message, entityId });
        } finally {
            this.state.isWaitingForResponse = false;
            this.emitEvent('ai_thinking_end', { entityId });
        }
    }

    // 生成AI回复
    private async generateAIResponse(message: string, context: ConversationContext): Promise<string> {
        // 检查AI服务是否配置
        if (!aiService.isConfigured()) {
            // 如果没有配置，显示配置界面
            if (!configUI.hasConfig()) {
                this.showConfigDialog();
                throw new Error('AI服务未配置，请先配置API密钥');
            } else {
                // 重新加载配置
                aiService.reloadConfiguration();
                if (!aiService.isConfigured()) {
                    throw new Error('AI配置无效，请重新配置');
                }
            }
        }

        // 获取生物个性
        const persona = getEntityPersona(context.entityType);
        if (!persona) {
            throw new Error('未找到生物个性配置');
        }

        // 更新游戏上下文
        context.gameContext = this.getGameContext(this.state.currentTarget!);

        // 调用AI服务生成回复
        return await aiService.generateResponse(message, context, persona);
    }

    // 显示配置对话框
    private showConfigDialog(): void {
        configUI.show((config) => {
            // 配置保存后重新加载AI服务
            aiService.reloadConfiguration();
            this.emitEvent('config_updated', { config });
        });
    }

    // 选择对话目标
    async selectTarget(entity: Entity): Promise<void> {
        if (!this.canChatWithEntity(entity)) {
            return;
        }

        // 使用目标选择器切换目标
        this.targetSelector.switchTarget(entity);
        await this.startConversation(entity);
        this.emitEvent('target_selected', { entity });
    }

    // 智能选择最佳对话目标
    async selectBestTarget(playerPosition: Vec3, entities: Entity[]): Promise<Entity | null> {
        const bestTarget = this.targetSelector.selectBestTarget(playerPosition, entities);
        
        if (bestTarget) {
            // 如果找到了最佳目标且与当前目标不同，开始新对话
            if (!this.state.currentTarget || this.state.currentTarget.getId() !== bestTarget.getId()) {
                await this.startConversation(bestTarget);
            }
            return bestTarget;
        } else {
            // 需求 5.5: 无生物时的提示信息显示
            if (this.state.isActive) {
                this.endConversation();
                this.emitEvent('no_targets_available', { message: '附近没有可对话的生物' });
            }
            return null;
        }
    }

    // 检测附近的生物
    findNearbyEntities(playerPosition: Vec3, entities: Entity[]): Entity[] {
        return entities.filter(entity => {
            if (!this.canChatWithEntity(entity)) {
                return false;
            }

            const distance = this.calculateDistance(playerPosition, entity.getPosition());
            return distance <= this.maxDetectionRange;
        });
    }

    // 检查是否可以与生物对话
    private canChatWithEntity(entity: Entity): boolean {
        if (!entity) {
            return false;
        }

        const entityType = entity.getType();
        if (!entityType) {
            return false;
        }

        // 检查是否有对应的个性配置
        const persona = getEntityPersona(entityType);
        return persona !== null;
    }

    // 计算距离
    private calculateDistance(pos1: Vec3, pos2: Vec3): number {
        const dx = pos1.x - pos2.x;
        const dy = pos1.y - pos2.y;
        const dz = pos1.z - pos2.z;
        return Math.sqrt(dx * dx + dy * dy + dz * dz);
    }

    // 检查目标是否仍在范围内
    checkTargetInRange(playerPosition: Vec3): boolean {
        if (!this.state.currentTarget) {
            return false;
        }

        // 使用目标选择器检查当前目标的有效性
        const isValid = this.targetSelector.checkCurrentTargetValidity(playerPosition);
        
        if (!isValid) {
            this.emitEvent('target_lost', { entity: this.state.currentTarget });
            this.endConversation();
            return false;
        }

        // 额外检查对话范围（比检测范围更大）
        const distance = this.calculateDistance(playerPosition, this.state.currentTarget.getPosition());
        if (distance > this.maxChatRange) {
            this.emitEvent('target_lost', { entity: this.state.currentTarget });
            this.endConversation();
            return false;
        }

        return true;
    }

    // 添加消息到对话历史
    private async addMessage(
        entityId: string, 
        sender: 'player' | 'entity', 
        content: string,
        options?: {
            messageType?: StoredChatMessage['messageType'];
            trigger?: StoredChatMessage['trigger'];
            importance?: StoredChatMessage['importance'];
        }
    ): Promise<void> {
        const conversation = this.conversations.get(entityId);
        if (!conversation) {
            return;
        }

        const message: ChatMessage = {
            id: this.generateMessageId(),
            timestamp: Date.now(),
            sender,
            content,
            entityId,
            entityType: conversation.entityType
        };

        // 添加到内存中的对话历史
        conversation.history.push(message);

        // 限制内存中的历史消息数量
        if (conversation.history.length > 50) {
            conversation.history = conversation.history.slice(-50);
        }

        // 保存到持久化存储
        try {
            await chatStorage.saveMessage(message, {
                messageType: options?.messageType || 'conversation',
                trigger: options?.trigger,
                gameContext: {
                    playerPosition: conversation.gameContext.playerPosition,
                    timeOfDay: conversation.gameContext.timeOfDay,
                    weather: conversation.gameContext.weather
                },
                importance: options?.importance || 'medium'
            });
        } catch (error) {
            console.error('Failed to save message to storage:', error);
        }

        this.emitEvent('message_received', { message });
    }

    // 从存储中加载对话历史
    private async loadConversationHistory(entityId: string, entityType: string): Promise<ChatMessage[]> {
        try {
            const storedMessages = await chatStorage.loadHistory(entityId, entityType, 50);
            // 转换为ChatMessage格式
            return storedMessages.map(msg => ({
                id: msg.id,
                timestamp: msg.timestamp,
                sender: msg.sender,
                content: msg.content,
                entityId: msg.entityId,
                entityType: msg.entityType
            }));
        } catch (error) {
            console.error('Failed to load conversation history:', error);
            return [];
        }
    }

    // 获取对话历史
    getConversationHistory(entityId: string): ChatMessage[] {
        const conversation = this.conversations.get(entityId);
        return conversation ? [...conversation.history] : [];
    }

    // 获取完整的存储历史记录
    async getStoredConversationHistory(entityId?: string, entityType?: string, limit?: number): Promise<StoredChatMessage[]> {
        try {
            return await chatStorage.loadHistory(entityId, entityType, limit);
        } catch (error) {
            console.error('Failed to get stored conversation history:', error);
            return [];
        }
    }

    // 获取游戏上下文
    private getGameContext(entity: Entity): GameContext {
        // 这个方法将由Game类设置的回调来提供实际数据
        if (this.gameContextProvider) {
            return this.gameContextProvider(entity);
        }
        
        // 默认上下文
        return {
            playerPosition: { x: 0, y: 0, z: 0 },
            timeOfDay: 'noon',
            weather: 'clear',
            nearbyBlocks: [],
            nearbyEntities: []
        };
    }

    // 设置游戏上下文提供者
    public setGameContextProvider(provider: (entity: Entity) => GameContext): void {
        this.gameContextProvider = provider;
    }

    // 生成消息ID
    private generateMessageId(): string {
        return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
    }

    // 事件系统
    addEventListener(type: ChatEventType, listener: Function): void {
        if (!this.eventListeners.has(type)) {
            this.eventListeners.set(type, []);
        }
        this.eventListeners.get(type)!.push(listener);
    }

    removeEventListener(type: ChatEventType, listener: Function): void {
        const listeners = this.eventListeners.get(type);
        if (listeners) {
            const index = listeners.indexOf(listener);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }

    private emitEvent(type: ChatEventType, data?: any): void {
        const listeners = this.eventListeners.get(type);
        if (listeners) {
            const event: ChatEvent = {
                type,
                data,
                timestamp: Date.now()
            };
            listeners.forEach(listener => listener(event));
        }
    }

    // 获取当前状态
    getState(): ChatState {
        return { ...this.state };
    }

    // 清除所有聊天记录
    async clearAllChatHistory(): Promise<void> {
        try {
            await chatStorage.clearAllHistory();
            // 清除内存中的对话
            this.conversations.clear();
            console.log('All chat history cleared');
        } catch (error) {
            console.error('Failed to clear chat history:', error);
            throw error;
        }
    }

    // 清除特定实体的聊天记录
    async clearEntityChatHistory(entityId: string, entityType: string): Promise<void> {
        try {
            await chatStorage.clearEntityHistory(entityId, entityType);
            // 清除内存中的对话
            this.conversations.delete(entityId);
            console.log(`Chat history cleared for ${entityType}_${entityId}`);
        } catch (error) {
            console.error('Failed to clear entity chat history:', error);
            throw error;
        }
    }

    // 获取存储统计信息
    getChatStorageStats() {
        return chatStorage.getStorageStats();
    }

    // 导出聊天记录
    async exportChatHistory(): Promise<string> {
        try {
            return await chatStorage.exportHistory();
        } catch (error) {
            console.error('Failed to export chat history:', error);
            throw error;
        }
    }

    // 导入聊天记录
    async importChatHistory(data: string): Promise<void> {
        try {
            await chatStorage.importHistory(data);
            // 清除内存中的对话，强制重新加载
            this.conversations.clear();
            console.log('Chat history imported successfully');
        } catch (error) {
            console.error('Failed to import chat history:', error);
            throw error;
        }
    }

    // 标记消息为已读
    async markMessagesAsRead(entityId: string, entityType: string): Promise<void> {
        try {
            await chatStorage.markMessagesAsRead(entityId, entityType);
        } catch (error) {
            console.error('Failed to mark messages as read:', error);
        }
    }

    // 获取未读消息数量
    getUnreadMessageCount(entityId?: string, entityType?: string): number {
        return chatStorage.getUnreadCount(entityId, entityType);
    }

    // 执行自动清理
    async performAutoCleanup(): Promise<void> {
        try {
            await chatStorage.performAutoCleanup();
        } catch (error) {
            console.error('Failed to perform auto cleanup:', error);
        }
    }

    // 获取目标选择器
    public getTargetSelector(): TargetSelector {
        return this.targetSelector;
    }

    // 获取在范围内的有效对话目标
    public getValidTargetsInRange(playerPosition: Vec3, entities: Entity[]): Entity[] {
        return this.targetSelector.getValidTargetsInRange(playerPosition, entities);
    }

    // 更新目标选择器的检测范围
    public setTargetDetectionRange(range: number): void {
        this.maxDetectionRange = range;
        this.targetSelector.setDetectionRange(range);
    }

    // 获取目标选择器状态
    public getTargetSelectorStatus(): {
        currentTarget: Entity | null;
        conversationInProgress: boolean;
        detectionRange: number;
        lastSwitchTime: number;
    } {
        return this.targetSelector.getStatus();
    }

    // 清理资源
    dispose(): void {
        this.endConversation();
        this.conversations.clear();
        this.eventListeners.clear();
        this.targetSelector.reset();
        chatStorage.dispose();
    }
}